<?php

namespace App\Http\Controllers;

use App\Models\AfterSalesRequest;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\LogisticsCompany;
use App\Http\Requests\StoreAfterSalesRequest;
use App\Services\AfterSalesService;
use Illuminate\Http\Request;
use Inertia\Inertia;

class AfterSalesController extends Controller
{
    protected AfterSalesService $afterSalesService;

    public function __construct(AfterSalesService $afterSalesService)
    {
        $this->afterSalesService = $afterSalesService;
    }
    /**
     * 售后申请列表
     */
    public function index(Request $request)
    {
        $requests = $this->afterSalesService->getAfterSalesRequestsForUser(
            auth()->id(),
            $request->only(['status', 'type', 'keyword'])
        );

        return Inertia::render('Shop/AfterSales/Index', [
            'requests' => $requests,
            'filters' => $request->only(['status', 'type', 'keyword']),
        ]);
    }

    /**
     * 创建售后申请页面
     */
    public function create(Request $request)
    {
        $orderNumber = $request->order_number;
        $order = null;

        if ($orderNumber) {
            $order = Order::with(['items.product', 'items.variant'])
                ->where('order_number', $orderNumber)
                ->where('user_id', auth()->id())
                ->first();

            if (!$order) {
                return redirect()->back()->with('error', '订单不存在或无权限访问');
            }

            // 使用服务层检查订单是否可以申请售后
            try {
                $this->afterSalesService->validateOrderForAfterSales($order);
            } catch (\Exception $e) {
                return redirect()->back()->with('error', $e->getMessage());
            }
        }

        // 获取启用的物流公司
        $logisticsCompanies = $this->afterSalesService->getLogisticsCompanies();

        return Inertia::render('Shop/AfterSales/Create', [
            'order' => $order,
            'logisticsCompanies' => $logisticsCompanies,
        ]);
    }

    /**
     * 提交售后申请
     */
    public function store(StoreAfterSalesRequest $request)
    {
        try {
            // 处理图片上传
            $images = [];
            if ($request->hasFile('images')) {
                foreach ($request->file('images') as $image) {
                    $path = $image->store('after-sales', 'public');
                    $images[] = $path;
                }
            }

            $data = $request->validated();
            $data['images'] = $images;

            // 服务层负责所有业务逻辑和权限检查
            $afterSalesRequest = $this->afterSalesService->createAfterSalesRequest($data, auth()->id());

            return redirect()->route('after-sales.show', $afterSalesRequest)
                ->with('success', '售后申请已提交，请等待审核');
        } catch (\Exception $e) {
            return redirect()->back()->with('error', '售后申请提交失败：' . $e->getMessage());
        }
    }

    /**
     * 售后申请详情
     */
    public function show(AfterSalesRequest $afterSalesRequest)
    {
        $this->authorize('view', $afterSalesRequest);

        $afterSalesRequest = $this->afterSalesService->getAfterSalesRequestDetails($afterSalesRequest->id);
        
        // 添加超时计算属性
        $afterSalesRequest->is_near_timeout = $afterSalesRequest->isNearTimeout();
        $afterSalesRequest->timeout_message = $afterSalesRequest->getTimeoutMessage();
        
        $logisticsCompanies = $this->afterSalesService->getLogisticsCompanies();

        return Inertia::render('Shop/AfterSales/Show', [
            'request' => $afterSalesRequest,
            'logisticsCompanies' => $logisticsCompanies,
        ]);
    }

    /**
     * 取消售后申请
     */
    public function cancel(AfterSalesRequest $afterSalesRequest)
    {
        $this->authorize('cancel', $afterSalesRequest);

        try {
            $this->afterSalesService->cancelAfterSalesRequest($afterSalesRequest);
            return redirect()->back()->with('success', '售后申请已取消');
        } catch (\Exception $e) {
            return redirect()->back()->with('error', $e->getMessage());
        }
    }



    /**
     * 生成退款金额计算说明
     */
    private function generateCalculationNote(float $price, int $quantity, float $refundAmount): string
    {
        return "按原价退款，单价：¥{$price}，数量：{$quantity}，计算：¥{$price} × {$quantity} = ¥{$refundAmount}";
    }

    /**
     * 提交物流信息
     */
    public function storeLogistics(Request $request, AfterSalesRequest $afterSalesRequest)
    {
        $this->authorize('submitLogistics', $afterSalesRequest);

        $request->validate([
            'company' => 'required|string|max:255',
            'tracking_number' => 'required|string|max:255',
            'sender_name' => 'nullable|string|max:255',
            'sender_phone' => 'nullable|string|max:20',
            'sender_address' => 'nullable|string|max:500',
            'note' => 'nullable|string|max:1000',
        ]);

        try {
            $this->afterSalesService->submitLogistics(
                $afterSalesRequest,
                $request->only(['company', 'tracking_number', 'sender_name', 'sender_phone', 'sender_address', 'note']),
                'user'
            );

            return redirect()->back()->with('success', '物流信息提交成功');
        } catch (\Exception $e) {
            return redirect()->back()->with('error', $e->getMessage());
        }
    }

    /**
     * 确认新商品已送达
     */
    public function confirmDelivered(AfterSalesRequest $afterSalesRequest)
    {
        $this->authorize('view', $afterSalesRequest);

        try {
            // 检查是否为换货申请且状态为新商品已寄出
            if ($afterSalesRequest->type !== AfterSalesRequest::TYPE_EXCHANGE) {
                return redirect()->back()->with('error', '只有换货申请才能确认送达');
            }

            if ($afterSalesRequest->extended_status !== AfterSalesRequest::EXTENDED_STATUS_NEW_SENT) {
                return redirect()->back()->with('error', '当前状态不允许确认送达');
            }

            // 标记新商品已送达
            $afterSalesRequest->markNewDelivered();

            return redirect()->back()->with('success', '已确认新商品送达，换货流程完成');
        } catch (\Exception $e) {
            return redirect()->back()->with('error', '确认送达失败：' . $e->getMessage());
        }
    }
}
